package com.example.demo.service.impl;

import com.example.demo.common.ErrorCode;
import com.example.demo.constant.CommonConstant;
import com.example.demo.context.UserContext;
import com.example.demo.entity.Admin;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.AdminMapper;
import com.example.demo.service.AdminService;
import com.example.demo.utils.JwtUtils;
import com.example.demo.vo.UserLoginVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public UserLoginVo login(String username, String password) {
        // 查询管理员
        Admin admin = adminMapper.findByUsername(username);
        System.out.println(admin);
        if (admin == null) {
            throw new BusinessException(ErrorCode.ADMIN_NOT_EXIST);
        }

        // 验证密码
        if (!password.equals(admin.getPassword())) {
            throw new BusinessException(ErrorCode.ADMIN_PASSWORD_ERROR);
        }

        // 验证状态
        if (admin.getStatus() != null && admin.getStatus() == 0) {
            throw new BusinessException(ErrorCode.ADMIN_DISABLED);
        }

        // 生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", admin.getId());
        claims.put("username", admin.getUsername());
        String token = jwtUtils.generateToken(claims, CommonConstant.UserType.ADMIN);

        // 返回登录信息

        
        return UserLoginVo.builder().token(token).build();
    }

    @Override
    public Admin getAdminInfo() {
        Long userId = UserContext.getUserId();
        Admin admin = adminMapper.selectById(userId);
        if (admin == null) {
            throw new BusinessException(ErrorCode.ADMIN_NOT_EXIST);
        }
        return admin;
    }
} 